package com.ruoyi.web.controller.system.api.cc;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.api.mapper.PlanDetailsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.framework.interceptor.Authentication;
import com.ruoyi.system.api.ResponseWithData;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.api.service.IServiceLogService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 服务日志 与服务1对1关联st_plan_detailsController
 * 
 * @author shihx
 * @date 2020-03-09
 */
@Controller
@RequestMapping("/api/cc/ServiceLog")
public class ServiceLogController extends BaseController
{


    @Autowired
    private IServiceLogService serviceLogService;

    @Autowired
    private PlanDetailsMapper planDetailsMapper;

    private static final Logger log = LoggerFactory.getLogger(ServiceLogController.class);

    /**
     * 保存日志接口
     * @methodName: saveServiceLog
     * @description: TODO
     * @param serviceLogVo
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: shihx
     * @date: 2020/3/9 14:17
    **/
    @Log(title = "保存日志接口", businessType = BusinessType.INSERT)
    @PostMapping("/saveServiceLog")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "保存日志接口", httpMethod = "POST", notes = "保存日志接口")
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功" ,response = ServiceLogVo.class)
    })
    public ResponseWithData<?> saveServiceLog(@RequestBody ServiceLogVo serviceLogVo){
        try {
            return serviceLogService.saveServiceLog(serviceLogVo);
        }catch (Exception e){
            e.printStackTrace();
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    /**
     * 更改日志接口
     * @methodName: editServiceLog
     * @description: TODO
     * @param serviceLogVo
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: wlf
     * @date: 2020/4/22 13:35
     **/
    @Log(title = "更改日志接口", businessType = BusinessType.UPDATE)
    @PostMapping("/editServiceLog")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "更改日志接口", httpMethod = "POST", notes = "更改日志接口")
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功" ,response = ServiceLogVo.class)
    })
    public ResponseWithData<?> editServiceLog(@RequestBody Map<String, Object> serviceLogVo){
        try {
            return serviceLogService.editServiceLog(serviceLogVo);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    /**
     * 获取接受任务时间、到达现场时间
     * @methodName: findSendTime
     * @description: TODO
     * @param serviceNo
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: wlf
     * @date: 2020/3/19 15:27
     **/
    @GetMapping (value = "/findSendTime")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "获取接受任务时间、到达现场时间", httpMethod = "GET", notes = "获取接受任务时间、到达现场时间")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "服务通知号",name="serviceNo",required = true,dataType="String",example="服务通知号"),
            @ApiImplicitParam(value = "工程师id",name="enginnerId",required = true,dataType="String",example="工程师id")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功")
    })
    public ResponseWithData<?> findSendTime(@RequestParam(value="serviceNo",required=true) String serviceNo, @RequestParam(value="enginnerId",required=true) String enginnerId){
        try {
            return serviceLogService.findSendTime(serviceNo, enginnerId);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    /**st_service_notice
     * 日志管理查询未关联服务报告的日志
     * @methodName: selectUnboundList
     * @description: TODO
     * @param serviceLog
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: wlf
     * @date: 2020/3/22 10:28
     **/
    @PostMapping("/selectUnboundList")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "工作日志——查询日志管理列表", httpMethod = "POST", notes = "查询日志列表")
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功" ,response = ServiceLogVo.class)
    })
    public ResponseWithData<?> selectUnboundList(@RequestBody Map<String, Object> serviceLog){
        try {
            List<Map<String, Object>> list = serviceLogService.selectUnboundList(serviceLog);
            return new ResponseWithData<>().success(list).msg("操作成功").code(200);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    /**
     * 查询未完成状态下 已关联服务报告的日志
     * @methodName: selectBoundList
     * @description: TODO
     * @param serviceLog
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: wlf
     * @date: 2020/5/21 16:08
     **/
    @PostMapping("/selectBoundList")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "查询未完成状态下 已关联服务报告的日志", httpMethod = "POST", notes = "查询未完成状态下 已关联服务报告的日志")
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功" ,response = ServiceLogVo.class)
    })
    public ResponseWithData<?> selectBoundList(@RequestBody Map<String, Object> serviceLog){
        try {
            List<Map<String, Object>> list = serviceLogService.selectBoundList(serviceLog);
            return new ResponseWithData<>().success(list).msg("操作成功").code(200);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    /**
     * 查询日志列表
     * @methodName: selectServiceLogList
     * @description: TODO
     * @param serviceLog
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: wlf
     * @date: 2020/3/21 16:43
     **/
    @PostMapping("/selectServiceLogList")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "根据查询日志列表", httpMethod = "POST", notes = "查询日志列表")
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功" ,response = ServiceLogVo.class)
    })
    public ResponseWithData<?> selectServiceLogList(@RequestBody ServiceLog serviceLog){
        try {
            List<ServiceLog> list = serviceLogService.selectServiceLogList(serviceLog);
            return new ResponseWithData<>().success(list).msg("操作成功").code(200);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }
    /**
     * 查询未关联的日志列表
     * @methodName: selectUnRelationServiceLogList
     * @description: TODO
     * @param serviceLog
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: bairuihua
     * @date: 2020/3/21 16:43
     **/
    @PostMapping("/selectUnRelationServiceLogList")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "根据查询日志列表", httpMethod = "POST", notes = "查询日志列表")
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功" ,response = ServiceLogVo.class)
    })
    public ResponseWithData<?> selectUnRelationServiceLogList(@RequestBody ServiceLog serviceLog){
        try {
            List<ServiceLog> list = serviceLogService.selectUnRelationServiceLogList(serviceLog);
            return new ResponseWithData<>().success(list).msg("操作成功").code(200);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }
    /**
     * 根据id查询日志详情
     * @methodName: selectServiceLogByID
     * @description: TODO
     * @param id
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: wlf
     * @date: 2020/3/21 16:43
     **/
    @GetMapping("/selectServiceLogByID")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "根据id查询日志详情", httpMethod = "GET", notes = "根据id查询日志详情")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "主键id", name = "id", required = true, dataType = "Long", paramType = "query"),
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功" ,response = ServiceLogVo.class)
    })
    public ResponseWithData<?> selectServiceLogByID(@RequestParam(value="id",required=true) Long id){
        try {
            ServiceLog serviceLog = serviceLogService.selectServiceLogById(id);
            return new ResponseWithData<>().success(serviceLog).msg("操作成功").code(200);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    /**
     * 获取日志信息
     * @methodName: getServiceLogList
     * @description: TODO
     * @param planId
     * @param enginnerId
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: shihx
     * @date: 2020-04-14 18:36
    **/
    @GetMapping("/getServiceLogList")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "获取日志列表", httpMethod = "GET", notes = "获取日志列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "计划表主键ID", name = "planId", required = true, defaultValue = "001", dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "工程师ID", name = "enginnerId", required = true, defaultValue = "001", dataType = "String", paramType = "query"),
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功")
    })
    public ResponseWithData<?> getServiceLogList(@RequestParam(value="planId",required=true) String planId,
                                                 @RequestParam(value="enginnerId",required=true) String enginnerId){
        try {

            Long lastPlanId;
            PlanDetails stPlanDetails = planDetailsMapper.selectStPlanDetailsById(Long.parseLong(planId));
            if(stPlanDetails!=null){
                if("1".equals(stPlanDetails.getState())){
                    //最后一个状态是不是1，返回最后一个状态不是1的plan
                    PlanDetails planDetails = getPlanDetailsListStateNotOne(stPlanDetails.getFseId(), stPlanDetails.getServiceNoticeId());
                    if(planDetails==null){
                        //没找到状态非1的计划
                        List<ServiceLog> serviceLogs=new ArrayList<>();
                        return new ResponseWithData<>().success(serviceLogs).msg("查询成功").code(200);
                    }
                    else {
                        lastPlanId = planDetails.getId();
                    }
                }
                else {
                    //状态非1
                    lastPlanId= Long.parseLong(planId);
                }
            }
            else {
                //根据计划id没找到计划信息
                List<ServiceLog> serviceLogs=new ArrayList<>();
                return new ResponseWithData<>().success(serviceLogs).msg("查询成功").code(200);
            }

            //获取日志列表
            ServiceLog serviceLog = new ServiceLog();
            serviceLog.setStPlanId(lastPlanId);
            serviceLog.setFseId(enginnerId);
            List<ServiceLog> serviceLogs = serviceLogService.selectServiceLogList(serviceLog);
            return new ResponseWithData<>().success(serviceLogs).msg("查询成功").code(200);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    private PlanDetails getPlanDetailsListStateNotOne(String fseId, Long serviceNoticeId){
        PlanDetails searchstPlanDetails =new PlanDetails();
        searchstPlanDetails.setFseId(fseId);
        searchstPlanDetails.setServiceNoticeId(serviceNoticeId);
         List<PlanDetails> planDetailsList = planDetailsMapper.selectStPlanDetailsList(searchstPlanDetails);
         if(planDetailsList!=null){
             for (PlanDetails planDetails : planDetailsList) {
                 if("1".equals(planDetails.getState())){
                   //不做操作
                 } else{
                     return planDetails;
                 }
             }
         }
         return null;
    }


}
